import axios from "axios";
import qs from "qs";
import router from "vue-router";
import Vue from 'vue'



if (process.env.NODE_ENV == 'development') { //开发环境
    Vue.prototype.$imgHost = 'http://localhost:3000'
}

if (process.env.NODE_ENV == 'production') { //生产环境
    Vue.prototype.$imgHost = ''
}


//请求拦截器：
axios.interceptors.request.use(config => {
    console.log('本次请求地址为：' + config.url);
    //获取本地存储的tocken:
    let curTocken = localStorage['appUser'] ? JSON.parse(localStorage['appUser']).token : ''
    if (curTocken) {
        config.headers.authorization = curTocken;
    }

    return config;
});

//响应拦截器：
axios.interceptors.response.use(config => {
    // if (config.data.code != 200) {
    //     alert(config.data.msg);
    // }

    if (config.data.code == 403) { //登录失效或访问路由受限
        router.push('/login');
    }

    return config;
});

//发送axios的get请求：
export function sendGet(url, params = {}, headers = {}) {
    //axios.get('/api/getbanner', { params: {}, headers: '' })
    return axios.get(url, { params, headers })
}

//发送axios的post请求：
export function sendPost(url, params = {}, isFile = false, headers = {}) {
    let datas = '';
    let forms = new FormData();
    if (isFile) { //params参数中含有文件上传
        for (let key in params) {
            forms.append(key, params[key])
        }
        datas = forms;
    } else { //params参数中不含文件上传
        datas = qs.stringify(params)
    }
    return axios.post(url, datas, { headers })
}